﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using NCD.ORMDbContext.Dapper;
using NCD.ORMDbContext.Entities;
using NCD.ORMDbContext.Enums;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NCD.ORMDbContext.EFCore
{

    /// <summary>
    /// 
    /// </summary>
    public abstract class EFCoreDBContext : DbContext
    {

        private IDbConnection _connection;
        private readonly EFCoreDBContextOptions _options;

        public IDbConnection Connection { get { return _connection; } }

        /// <summary>
        /// 用于给子类重写的创建连接的抽象方法, 子类连接哪种数据库,就创建哪种数据库的链接
        /// </summary>
        /// <param name="connectionString">连接字符串</param>
        /// <returns></returns>
        protected abstract IDbConnection CreateConnection(string connectionString, DbTypeNameEnum dbType);


        // Define your DbSets here
        public DbSet<UserInfo> UserInfo { get; set; }

        protected EFCoreDBContext(IOptions<EFCoreDBContextOptions> optionsAccessor)
        {
            //构造函数中赋值用于传递到OnConfiguring方法
            _options = optionsAccessor.Value;
            _connection = this.CreateConnection(_options.Connection, _options.DbType);
            _connection.Open();
        }

        // This method is called for each DbContext instance that is created.
        // Configure the database (and other options) here
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                var connectionString = _options.Connection;
                var _dbType = _options.DbType;
                if (_dbType == DbTypeNameEnum.MsSql)
                {
                    optionsBuilder.UseSqlServer(connectionString);
                }
                else
                {
                    optionsBuilder.UseMySQL(connectionString);
                }
            }
        }
    }
}
